/**
 @Name: user
 */
layui.define(['laypage', 'tbynet'], function(exports) {
	var $ = layui.$
	,form = layui.form
	,layer = layui.layer
	,laytpl = layui.laytpl
	,laypage = layui.laypage
	,tbynet = layui.tbynet;

	/**
     * 文章可见性设置
     */
	form.on('radio(visibility)', function(data){
		"public" != data.value ? ($("#sticky").prop("checked", false), $("#sticky-span").hide()) : $("#sticky-span").show(), 
		 "password" != data.value ? $("#password-span").hide() : ($("#password-span").show(), $("#sticky").prop("checked", false)),
		form.render('checkbox')
	});

	/**
     * 编辑可见性设置
     */
  	$(".edit-visibility").click(function(e) {
        e.preventDefault(), 
        $("#post-visibility-select").is(":hidden") && ($("#post-visibility-select").slideDown("fast", function() {
        	$("#post-visibility-select").find('input[type="radio"]').first().focus()
        }), 
        $(this).hide())
    });

  	/**
     * 取消可见性设置
     */
  	$("#post-visibility-select").find(".cancel-post-visibility").click(function(e) {
  		$("#post-visibility-select").slideUp("fast"), 
        $("#visibility-radio-" + $("#hidden-post-visibility").val()).prop("checked", !0), 
        $("#post_password").val($("#hidden-post-password").val()), 
        $("#sticky").prop("checked", $("#hidden-post-sticky").prop("checked")), 
//        $("#post-visibility-display").html(new Date($("#hidden_aa").val(), $("#hidden_mm").val() - 1, $("#hidden_jj").val(), $("#hidden_hh").val(), $("#hidden_mn").val())), 
        $(".edit-visibility").show().focus(), 
        //g(), 
        e.preventDefault()
    });

    /**
     * 保存可见性设置
     */
  	$("#post-visibility-select").find(".save-post-visibility").click(function(e) {
  		$("#post-visibility-select").slideUp("fast"), 
        $(".edit-visibility").show().focus(), 
        //g(), 
        "public" != $("#post-visibility-select").find("input:radio:checked").val() && $("#sticky").prop("checked", !1), 
        h = $("#sticky").prop("checked") ? "Sticky" : "", 
        $("#post-visibility-display").html(postL10n[$("#post-visibility-select").find("input:radio:checked").val() + h]), 
        e.preventDefault()
    });

  	/**
     * 时间戳编辑
     */
  	$("#timestampdiv").siblings("a.edit-timestamp").click(function(e) {
  		$("#timestampdiv").is(":hidden") && ($("#timestampdiv").slideDown("fast", function() {
            $("input, select", $("#timestampdiv").find(".timestamp-wrap")).first().focus()
        }), $(this).hide()), 
        e.preventDefault()
    });
  	$("#timestampdiv").find(".cancel-timestamp").click(function(e) {
  		$("#timestampdiv").slideUp("fast").siblings("a.edit-timestamp").show().focus(), 
        e.preventDefault()
    });
  	$("#timestampdiv").find(".save-timestamp").click(function(e) {
  		$("#timestampdiv").slideUp("fast"), 
  		$("#timestampdiv").siblings("a.edit-timestamp").show().focus(), 
        e.preventDefault()
    });
  	$("#post-status-select").siblings("a.edit-post-status").click(function(e) {
  		$("#post-status-select").is(":hidden") && ($("#post-status-select").slideDown("fast", function() {
  			$("#post-status-select").find("select").focus()
        }), 
        $(this).hide()), 
        e.preventDefault()
    });
  	$("#post-status-select").find(".save-post-status").click(function(e) {
  		$("#post-status-select").slideUp("fast").siblings("a.edit-post-status").show().focus(), 
        e.preventDefault()
    });
  	$("#post-status-select").find(".cancel-post-status").click(function(e) {
  		$("#post-status-select").slideUp("fast").siblings("a.edit-post-status").show().focus(), 
        $("#post_status").val($("#hidden_post_status").val()), 
        e.preventDefault()
    });

  	/**
     * 分类目录操作
     */
  	$('#category-add-toggle').on('click', function(){
  		if($('#category-add').is(':hidden')){
  			$('#category-add').show();
  		} else {
  			$('#category-add').hide();
  		}
  	});
  	
  	$('#link-post_tag').on('click', function(){
  		if($('#tagcloud-post_tag').is(':hidden')){
  			$('#tagcloud-post_tag').show();
  		} else {
  			$('#tagcloud-post_tag').hide();
  		}
  	});
  	
  	$('#new-tag-post_tag').on('focus', function(e){
  		showTag($(this).val());
  	});
  	$('#new-tag-post_tag').on('keyup', function(e){
  		showTag($(this).val());
  	});
  	$('#taglist').on('click', 'li', function(e){
  		var tag = $(this).text();
  		var str = $('#new-tag-post_tag').val();
  		
  		var array = str.split('、');
  		var q = array.pop();
  		
  		if(str.indexOf(tag) == -1 || q == tag) {
  			array.push(tag);
  		}
  		
  		$('#new-tag-post_tag').val(array.join('、') + '、');
  		hideTag();
  	});
  	$('#tagadd').on('click', function(e){
  		var newtag = $('#new-tag-post_tag').val();
  		if(null == newtag || '' == newtag) {
  			return;
  		}
  		$('#new-tag-post_tag').val('');
  		
  		$('#tax-tag-post_tag').val($('#tax-tag-post_tag').val() + newtag);
  		var taxtag = $('#tax-tag-post_tag').val();
  		
  		var html = '';
  		var array = taxtag.split('、');
  		for(var i in array) {
  			var tag = array[i];
  			if(null == tag || '' == tag) {
  				continue;
  			}
  			html += '<li data="'+ tag +'">\
				<button type="button" class="ntdelbutton">\
					<span class="layui-icon layui-icon-close-fill" style="color:#0073aa;"></span>\
					<span class="screen-reader-text">移除项目：'+ tag +'</span>\
				</button>\
				&nbsp;'+ tag +'\
			</li>';
  		}
  		$('.tagchecklist').html(html);
  	});
  	$('.tagchecklist').on('click', 'li', function(){
  		var tag = $(this).attr('data');
  		var taxtag = $('#tax-tag-post_tag').val();
  		var array = taxtag.split('、');
  		array = $.grep(array, function(value) {
  			 return value != tag;
  		});
  		$('#tax-tag-post_tag').val(array.join('、') + '、');
  		$(this).remove();
  	});
  	
  	function showTag(str){
  		if(null == str || '' == str || 2 > str.length) {
  			hideTag();
  			return;
  		}
  		
  		var q = str.substring(str.lastIndexOf('、') + 1);
  		if(null == q || '' == q || 2 > q.length) {
  			hideTag();
  			return;
  		}
  		
  		if(!$('#new-tag-post_tag').hasClass('ui-autocomplete-loading')){
  			$('#new-tag-post_tag').addClass('ui-autocomplete-loading');
  		}
  		
  		tbynet.ajax('/admin/tag/search', {q: q}, function(res){
  			setInterval(function(){
  				if($('#new-tag-post_tag').hasClass('ui-autocomplete-loading')){
  	  				$('#new-tag-post_tag').removeClass('ui-autocomplete-loading');
  	  			}
  			}, 1000);
  			
  			if(res.data.totalRow == 0) {
  				hideTag();
  			} else {
  				var html = '';
  	  			layui.each(res.data.list, function(index, item){
  	  				html += '<li class="ui-menu-item" tabindex="-1">'+ item.name +'</li>';
  	  			});
  	  			$('#taglist').html(html);
  	  			
  	  			$('#taglist').slideDown("fast");
  	  			$("body").bind("mousedown", onBodyDown);
  			}
  		});
  	}
  	function hideTag(){
  		$('#taglist').fadeOut("fast");
  		$("body").unbind("mousedown", onBodyDown);
  	}
  	function onBodyDown(event) {
		if (!(event.target.id == "new-tag-post_tag" || event.target.id == "taglist" || $(event.target).parents("#taglist").length>0)) {
			hideTag();
		}
	}
  	
  	$('body').on('click', '#set-post-thumbnail', function(){
  		layer.open({
  			type: 2,
  			title: '特色图片',
  			skin: 'finder',
  			shadeClose: true,
  			shade: 0.8,
  			area: ['90%', '90%'],
  			content: '/admin/attachment/finder' //iframe的url
  		});
  	});
  	
	//表单提交返回成功后才执行这个方法
	tbynet.form['/admin/post/save'] = function(data, required, res){
		layer.msg(res.msg, {
			offset: '15px'
			,icon: 1
			,time: 1000
		}, function(){
			location.href = '/admin/post';
		});
	}; 
	
	tbynet.form['/admin/post/update'] = function(data, required, res){
		layer.msg(res.msg, {
			offset: '15px'
			,icon: 1
			,time: 1000
		}, function(){
			location.href = '/admin/post';
		});
	};
	
    // 当前筛选参数
    var currentFilters = {
        status: getUrlParam('post_status') || '',
        date: getUrlParam('m') || '0',
        category: getUrlParam('cat') || '0',
        search: getUrlParam('q') || '',
        sticky: getUrlParam('show_sticky') || '0'
    };

    /**
     * 获取URL参数
     */
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
    }

    /**
     * 构建筛选参数
     */
    function buildFilterParams() {
        var params = {};

        if (currentFilters.status) params.status = currentFilters.status;
        if (currentFilters.date && currentFilters.date !== '0') params.m = currentFilters.date;
        if (currentFilters.category && currentFilters.category !== '0') params.cat = currentFilters.category;
        if (currentFilters.tag && currentFilters.tag !== '0') params.tag = currentFilters.tag;
        if (currentFilters.search) params.q = currentFilters.search;
        if (currentFilters.sticky === '1') params.sticky = true;

        return params;
    }

    /**
     * 更新URL但不刷新页面
     */
    function updateUrl(params) {
        var queryString = Object.keys(params).map(function(key) {
            return key + '=' + encodeURIComponent(params[key]);
        }).join('&');

        var newUrl = window.location.pathname + (queryString ? '?' + queryString : '');
        window.history.pushState({path: newUrl}, '', newUrl);
    }

    /**
     * 初始化筛选事件
     */
    function initFilters() {
        // 状态筛选链接
        $('.subsubsub a').on('click', function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            window.location.href = url;
        });

        // 搜索表单提交
        $('#posts-filter').on('submit', function(e) {
            e.preventDefault();
            currentFilters.search = $('#post-search-input').val();
            search(1);
        });

        // 筛选按钮
        $('#filter-action').on('click', function() {
            currentFilters.date = $('#filter-by-date').val();
            currentFilters.category = $('#cat').val();
            currentFilters.tag = $('#tag').val(); // 新增标签筛选
            search(1);
        });

        // 批量操作
        $('#doaction, #doaction2').on('click', function() {
            var action = $(this).closest('.bulkactions').find('select').val();
            if (action === '-1') {
                layer.msg('请选择批量操作');
                return;
            }
            gather.batch(action);
        });

        // 全选/全不选
        // 监听全选复选框
        form.on('checkbox(checkall)', function(data){
            var checked = data.elem.checked;
            $('input[name="post_ids"]').prop('checked', checked);
            form.render('checkbox');
        });
        // 监听单个文章复选框
        form.on('checkbox(postCheckbox)', function(data) {
            updateCheckAllStatus();
        });
        /**
         * 更新全选复选框状态
         */
        function updateCheckAllStatus() {
            var totalCheckboxes = $('input[name="post_ids"]').length;
            var checkedCheckboxes = $('input[name="post_ids"]:checked').length;
            var allChecked = totalCheckboxes > 0 && totalCheckboxes === checkedCheckboxes;

            $('#check-all, #check-all-footer').prop('checked', allChecked);
            form.render('checkbox');
        }

        // 清空回收站
        $('#empty-trash, #empty-trash-bottom').on('click', function() {
            layer.confirm('确定要永久删除回收站中的所有文章吗？此操作不可恢复！', function(index) {
                tbynet.ajax('/admin/post/batch', {
                    action: 'delete',
                    post_ids: 'all'
                }, function(res) {
                    layer.msg(res.msg, {
                        offset: '15px',
                        icon: 1,
                        time: 1000
                    }, function() {
                        location.reload();
                    });
                });
                layer.close(index);
            });
        });

        // 初始化筛选表单值
        $('#filter-by-date').val(currentFilters.date);
        $('#cat').val(currentFilters.category);
        $('#post-search-input').val(currentFilters.search);
        form.render('select');
    }

    var gather = {
        /**
         * 搜索文章
         */
        search: function(curr) {
            search(curr);
        },

        /**
         * 移至回收站
         */
        trash: function(id) {
            tbynet.ajax('/admin/post/trash', {post: id}, function(res){
                layer.msg(res.msg, {
                    offset: '15px',
                    icon: 1,
                    time: 1000
                }, function(){
                    location.reload();
                });
            });
        },

        /**
         * 恢复文章
         */
        restore: function(id) {
            tbynet.ajax('/admin/post/restore', {post: id}, function(res){
                layer.msg(res.msg, {
                    offset: '15px',
                    icon: 1,
                    time: 1000
                }, function(){
                    location.reload();
                });
            });
        },

        /**
         * 永久删除文章
         */
        delete: function(id) {
            layer.confirm('确定要永久删除这篇文章吗？此操作不可恢复！', function(index){
                tbynet.ajax('/admin/post/delete', {post: id}, function(res){
                    layer.msg(res.msg, {
                        offset: '15px',
                        icon: 1,
                        time: 1000
                    }, function(){
                        location.reload();
                    });
                });
                layer.close(index);
            });
        },

        /**
         * 批量操作
         */
        batch: function(action) {
            var selectedPosts = getSelectedPosts();
            if (selectedPosts.length === 0) {
                layer.msg('请选择要操作的文章');
                return;
            }

            var message = '';
            switch(action) {
                case 'trash':
                    message = '确定要将选中的文章移到回收站吗？';
                    break;
                case 'delete':
                    message = '确定要永久删除选中的文章吗？此操作不可恢复！';
                    break;
                case 'restore':
                    message = '确定要恢复选中的文章吗？';
                    break;
            }

            layer.confirm(message, function(index){
                tbynet.ajax('/admin/post/batch', {
                    action: action,
                    post_ids: selectedPosts
                }, function(res){
                    layer.msg(res.msg, {
                        offset: '15px',
                        icon: 1,
                        time: 1000
                    }, function(){
                        location.reload();
                    });
                });
                layer.close(index);
            });
        }
    };

    /**
     * 获取选中的文章ID
     */
    function getSelectedPosts() {
        var selected = [];
        $('input[name="post_ids"]:checked').each(function(){
            selected.push($(this).val());
        });
        return selected;
    }

    /**
     * 搜索函数
     */
    function search(curr) {
        if($('#post-page-tpl').length == 0) {
            return;
        }

        var params = buildFilterParams();
        params.page = curr || 1;

        // 更新URL
        updateUrl(params);

        tbynet.ajax('/admin/post/search', params, function(res){
            if(res.data.totalRow == 0) {
                $('table tbody').html('<tr><td colspan="7">找不到文章。</td></tr>');
                $('.tablenav-pages').hide();
            } else {
                laytpl($('#post-page-tpl').html()).render(res.data.list, function(html){
                    $('table tbody').html(html);
                });
                $('.tablenav-pages').show();
            }

            // 更新分页
            laypage.render({
                elem: $('.tablenav-pages'),
                count: res.data.totalRow,
                limit: res.data.pageSize,
                curr: curr || 1,
                layout: ['count', 'prev', 'page', 'next'],
                jump: function(obj, first){
                    if(!first){
                        search(obj.curr);
                    }
                }
            });

            form.render();
        });
    }
	
	// 初始化
    $(function() {
        initFilters();
        search(1);
    });

    exports('post', gather);
});